package com.mzplayer.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

/**
 * @Package: com.mzplayer.widget
 * @ClassName: FlagView
 * @Description: java类作用描述
 * @Author: 麦子
 * @QQ: 3332174009
 * @CreateDate: 2021/8/4 20:06
 */
public class AutoTextView extends View {
    private final Paint paint;
    private String text;
    private int textWidth;
    private float textSize;
    private int maxWidth;
    private int maxSize;

    public AutoTextView(Context context) {
        this(context, null);
    }

    public AutoTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AutoTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        paint = new Paint();
    }

    public void setTextColor(int textColor) {
        paint.setColor(textColor);
        invalidate();
    }

    public void setText(String text) {
        this.text = text;
        invalidate();
    }

    public void setTextSize(float textSize) {
        this.textSize = textSize;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if(maxSize > 0 && maxWidth > 0) {
            countTextSize();
            canvas.drawText(text, (maxWidth - textWidth) / 2f, (maxSize - textSize) / 2f + textSize, paint);
        }
    }

    protected void countTextSize() {
        if (textSize <= 0) {
            textSize = maxSize;
        }
        while (true) {
            paint.setTextSize(textSize);
            textWidth = (int) paint.measureText(text);
            if (textWidth <= maxWidth && textSize <= maxSize) {
                break;
            } else {
                --textSize;
            }
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        maxWidth = w;
        maxSize = h;
        invalidate();
    }
}
